/*
 * @Author: Seven
 * @Date: 2021-11-28 20:47:02
 * @LastEditors: Seven
 * @LastEditTime: 2021-11-28 20:59:54
 * @FilePath: \def-standard\src\utils\des.js
 * @Description: 
 */
import cryptoJs from 'crypto-js';

//随机生成指定数量的16进制key
export const generatekey = (num) => {
    let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let key = "";
    for (let i = 0; i < num; i++) {
        let randomPoz = Math.floor(Math.random() * library.length);
        key += library.substring(randomPoz, randomPoz + 1);
    }
    return key;
}

//DES加密
export const encryptDes = (message, key) => {
    let keyHex = cryptoJs.enc.Utf8.parse(key)
    let option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 }
    let encrypted = cryptoJs.DES.encrypt(message, keyHex, option)
    return encrypted.ciphertext.toString()
}


//DES解密
export const decryptDes = (message, key) => {
    let keyHex = cryptoJs.enc.Utf8.parse(key)
    let decrypted = cryptoJs.DES.decrypt(
          {
              ciphertext: cryptoJs.enc.Hex.parse(message)
          },
          keyHex,
          {
              mode: cryptoJs.mode.ECB,
              padding: cryptoJs.pad.Pkcs7
          }
    )
    return decrypted.toString(cryptoJs.enc.Utf8)
}
